<?php
include_once APPLICATION_PATH . "/models/Province.php";
include_once APPLICATION_PATH . "/models/District.php";
include_once APPLICATION_PATH . "/models/Agent.php";
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class Admin_DistrictController extends Zend_Controller_Action {

    public function init() {
        $bootstrap = $this->getInvokeArg("bootstrap");
        $this->aConfig = $bootstrap->getOptions();
        $this->view->aConfig = $this->aConfig;
        $this->model = new Model_District();
        $this->modelMapper = new Model_DistrictMapper();
        $this->AgentmodelMapper = new Model_AgentMapper();
    }
    
    public function indexAction(){
    }
    
    public function addAction() {
        if ($this->getRequest()->isPost()) {   
            $redirectUrl = $this->aConfig["site"]["url"] . "admin/district/list";
            if (isset($_POST["id"])) {
                $this->model->setId($_POST["id"]);
            }
            if (isset($_POST["district_code"])) {
                $this->model->setDistrictCode($_POST["district_code"]);
            }
            if (isset($_POST["name_district"])) {
                $this->model->setName($_POST["name_district"]);
            }
            if (isset($_POST["order_district"])) {
                $this->model->setOrder($_POST["order_district"]);
            }
            if (isset($_POST["status_district"])) {
                $status = 1;
            } else {
                $status = 0;
            }
            if (isset($_POST["province_id"])) {
                $this->model->setProvince_Id($_POST["province_id"]);
            }
            $this->model->setStatus($status);
            $this->model->setCreated(date("Y/m/d H:i:s"));
            $this->model->setCreated_By(GlobalLib::getLoginId());
            $this->model->setModified(date("Y/m/d H:i:s"));
            $this->model->setModified_By(GlobalLib::getLoginId());
            $this->modelMapper->save($this->model);
            $this->_redirect($redirectUrl);
        }
        $this->view->item = $this->model;
    }
    
  
    
    public function editAction(){
        $id= $this->_getParam("id","");
        $redirectUrl=$this->aConfig["site"]["url"]."admin/district/list";
        if(empty($id)){
            $this->_redirect($redirectUrl);
        }
        $this->modelMapper->find($id,$this->model);
        $getId=$this->model->getId();
        if(empty($getId)){
             $this->_redirect($redirectUrl);
        }
        if($this->getRequest()->isPost()){
            if(isset($_POST["id"])){
                $this->model->setId($_POST["id"]);
            }
            if (isset($_POST["district_code"])) {
                $this->model->setDistrictCode($_POST["district_code"]);
            }
            if(isset($_POST["name_district"])){
                $this->model->setName($_POST["name_district"]);
            }
            if(isset($_POST["order_district"])){
                $this->model->setOrder($_POST["order_district"]);
            }
            if(isset($_POST["status_district"])){
                $status=1;
            } else {
                $status=0;
            }
            if (isset($_POST["province_id"])) {
                $this->model->setProvince_Id($_POST["province_id"]);
            }            
            $this->model->setStatus($status);
            $this->model->setModified(date("Y/m/d H:i:s"));
            $this->model->setModified_By(GlobalLib::getLoginId());
            $this->modelMapper->save($this->model);
            $this->_redirect($redirectUrl);
        }
        
        $this->view->item=$this->model;
    }    
    public function listAction(){
        $this->view->controller = $this;
        $this->view->item=$this->modelMapper->fetchAll();
    }    
    
    public function serviceAction(){
        $this->_helper->layout->disableLayout();
        foreach ($this->modelMapper->fetchAll() as $items ) {
            $menber[]=array(
                'Id'=>$items->getId(),
                'DistrictCode'=>$items->getDistrictCode(),
                'DistrictName'=>$items->getName(),
                'ProvinceName'=> GlobalLib::getName('province',$items->getProvince_Id(),'name'),
                'Order'=>$items->getOrder()
            );
        }
        echo json_encode($menber);
        exit();
    }
    
    public function getdistrictAction(){
          $this->_helper->layout()->disableLayout();
                $districtHTML = '<select name="dictrict_id" style="width: 386px;"><option value=""></option></select>';
                if ($this->_request->isPost()) {
                    $province_id = $this->_getParam("province_id", "");
                    if (is_numeric($province_id)) {
                        $districtHTML = GlobalLib::getCombo('district_id', 'district', 'id', 'name', 0, false, 'where province_id=' . $province_id);
                    }
                }
                $districtHTML = $districtHTML;
                echo '[{"html":\'' . $districtHTML . '\'}]';
                exit;
    }
    
    public  function confirmdeleteAction()
    {
        $id = $this->_getParam("id","0");
        $count = 0;
        foreach($this->AgentmodelMapper->fetchAll() as $item)
        {
            if($item->getDistrict_Id()==$id) $count= $count+1;
        }
        echo $count;
        exit();
    }

    public function deleteAction(){
        $id= $this->_getParam("id","");
        $redirectUrl=$this->aConfig["site"]["url"]."admin/district/list";               
        $this->modelMapper->delete($id);
        $this->_redirect($redirectUrl);
    }
    
    public function exportAction() {
        $this->_helper->layout->disableLayout();
        if ($this->getRequest()->isPost()) {
            $objPHPExcel = new PHPExcel();
            $objPHPExcel->setActiveSheetIndex(0);
            $rowCount = 4;
            $stt=1;
            $objPHPExcel->getActiveSheet()->setCellValue('B3', "STT");
            $objPHPExcel->getActiveSheet()->setCellValue('C3', "Mã code");
            $objPHPExcel->getActiveSheet()->setCellValue('D3', "Tên");
            
            foreach ($this->modelMapper->fetchAll() as $items) {
                if($items->getDistrictCode()==NULL){
                    $district_code="Không Có";
                } else {
                    $district_code=$items->getDistrictCode();
                }
                $objPHPExcel->getActiveSheet()->setCellValue('B' . $rowCount, $stt);
                $objPHPExcel->getActiveSheet()->setCellValue('C' . $rowCount, $district_code);
                $objPHPExcel->getActiveSheet()->setCellValue('D' . $rowCount, $items->getName());                
                $rowCount++;
                $stt++;
            }
            $objPHPExcel->getActiveSheet()->mergeCells('A1:B2');
            $objPHPExcel->getActiveSheet()->mergeCells('C1:E2');
            $objPHPExcel->getActiveSheet()->setCellValue('C1', "Danh Sách Tỉnh");
            $style_alignment = array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $objPHPExcel->getActiveSheet()->getStyle("B3:L" . $rowCount)->getAlignment()->applyFromArray($style_alignment);
            $styleArray = array(
                'borders' => array(
                    'allborders' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                    ),
                ),
            );
            $styledataArray = array(
                'font' => array(
                    'bold' => true,
                    'color' => array('rgb' => '080808'),
                    'size' => 15,
                    'name' => 'Times New Roman'
            ));
            $styletitleArray=array(
                'font' => array(
                    'bold' => true,
                    'color' => array('rgb' => '080808'),
                    'size' => 10,
                    'name' => 'Times New Roman')
            );
            $objPHPExcel->getActiveSheet()->getStyle('C1')->getAlignment()->applyFromArray($style_alignment);
            $objPHPExcel->getActiveSheet()->getStyle('C1')->applyFromArray($styledataArray);
            $objPHPExcel->getActiveSheet()->getStyle('B3:L3')->applyFromArray($styletitleArray);
            $objPHPExcel->getActiveSheet()->getStyle('B3:E' . ($rowCount - 1))->applyFromArray($styleArray);
            foreach (range('B', 'E') as $columnID) {
                $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
            }
            $filename='DanhSachQuanHuyen '.date('m-Y').'.xls';
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename='.$filename);
            header('Cache-Control: max-age=0');
           $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
            $objWriter->save('php://output');
            exit();
        }
    }
    
    public function checkdistrictcodeAction(){
          $this->_helper->layout()->disableLayout();
         if($this->_request->isPost()){
             $district_code= $this->_getParam("district_code","");
             $id= $this->modelMapper->findidbycode($district_code);
             if($id !=0){
                 $menber[]=array(
                     'code'=>1,
                     'message'=>'Mã code này đã tồn tại. Vui lòng kiểm tra và nhập lại'
                         );  
             } else {
                  $menber[]=array(
                     'code'=>0,
                     'message'=>'');
             }
             echo json_encode($menber);
             exit();
         }  
    }
    public function checkdistrictnameAction(){
        $this->_helper->layout()->disableLayout();
        if($this->_request->isPost()){
            $district_name=$this->_getParam("district_name","");
            $id=$this->modelMapper->findidbyname($district_name);
            if($id !=0){
                 $menber[]=array(
                     'code'=>1,
                     'message'=>'Tên tỉnh đã tồn tại.Vui lòng kiểm tra và nhập lại'
                         );  
             } else {
                  $menber[]=array(
                     'code'=>0,
                     'message'=>''
                         );  
             }
             echo json_encode($menber);
             exit();
        }
    }
    
}
